package com.lqk.springbootminio.service.impl;

import com.lqk.springbootminio.config.MinioTemplate;
import com.lqk.springbootminio.properties.MinioConfigProperties;
import com.lqk.springbootminio.service.OssService;
import com.lqk.springbootminio.utils.MinioUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author liqiankun@nnuo.com
 * @date 2023/3/24 15:05
 * @description
 **/
@Slf4j
@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private MinioTemplate minioTemplate;

    @Autowired
    private MinioConfigProperties properties;

    @Autowired
    private HttpServletResponse response;

    @Override
    public String upload(MultipartFile file) {
        try {
            //文件名
            String newFileName = MinioUtils.spliceFilePath(file.getOriginalFilename());
            //类型
            String contentType = file.getContentType();
            // 上传后的文件路径
            return minioTemplate.uploadFile(properties.getBucketName(), file, newFileName, contentType);
        } catch (Exception e) {
            log.error("上传失败");
            return "上传失败";
        }
    }

    @Override
    public void removeFile(String fileName) {
        minioTemplate.removeFile(properties.getBucketName(), fileName);
    }

    @Override
    public String getFileStatusInfo(String fileName) {
        return minioTemplate.getFileStatusInfo(properties.getBucketName(), fileName);
    }

    @Override
    public String getPresignedObjectUrl(String fileName) {
        return minioTemplate.getPresignedObjectUrl(properties.getBucketName(), fileName);
    }

    @Override
    public void download(String fileName) {
        InputStream fileInputStream = null;
        try {
            fileInputStream = minioTemplate.getObject(properties.getBucketName(), fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载失败:{}",e.getMessage());
        } finally {
            try{
                if (fileInputStream != null){
                    fileInputStream.close();
                }
            } catch (IOException e){
                log.error("关闭文件流异常");
            }
        }
    }

}
